import React from 'react';
import { Checkbox } from 'antd';

const CheckboxGroup = Checkbox.Group;

class ModuleItem extends React.Component{
  static Prototypes: {
    plainOptions: PropTypes.array.isRequired,
    changeMenus: PropTypes.func.isRequired,
    itemId: PropTypes.string.isRequired
  }

  constructor(props) {
    super(props);

    let options = this.props.plainOptions;
    let defaultCheckedList = [];
    options.kids.map(function(opt) {
      if(opt.using == 1) {
        defaultCheckedList.push(opt.value);
      }
    });
    this.state= {
      checkedList: defaultCheckedList,
      indeterminate: true,
      checkAll: options.using ? true : false
    }
  }

  onChange(checkedList) {
    let plainOptions = this.props.plainOptions.kids;

    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < plainOptions.length),
      checkAll: checkedList.length === plainOptions.length
    });
    
    this.props.changeMenus({
      key: this.props.itemId,
      data: checkedList,
      add: true,
      force: true
    });
  }

  onCheckAllChange(e) {
    let plainOptions = this.props.plainOptions.kids;
    let defaultCheckedList = [];
    plainOptions.map(function(opt) {
      defaultCheckedList.push(opt.value);
    });
    this.setState({
      checkedList: e.target.checked ? defaultCheckedList : [],
      indeterminate: false,
      checkAll: e.target.checked
    });

    this.props.changeMenus({
      key: this.props.itemId,
      data: defaultCheckedList,
      add: e.target.checked,
      force: false
    });
  }

  /**
   * 强制取消选中
   */
  forceUnselectAll() {
    let plainOptions = this.props.plainOptions.kids;
    let defaultCheckedList = [];
    plainOptions.map(function(opt) {
      defaultCheckedList.push(opt.value);
    });
    this.setState({
      checkedList: [],
      indeterminate: false,
      checkAll: false
    });
  }

  render() {
    return (
      <div className="module-item">
        <div className="module-title">
          <Checkbox
            indeterminate={this.state.indeterminate}
            onChange={this.onCheckAllChange.bind(this)}
            checked={this.state.checkAll}
          >
          {this.props.plainOptions.label}
          </Checkbox>
        </div>
        <CheckboxGroup ref="group" options={this.props.plainOptions.kids} value={this.state.checkedList} onChange={this.onChange.bind(this)} />
      </div>
    );
  }
}; 

export default ModuleItem;






